<?php
/**
 * 控制器
 * 
 * Copyright (c) 2014~2019 https://desion.net All rights reserved.
 * Author: 阿林 QQ:120867629 <linhong00@gmail.com>
 */
declare (strict_types = 1);
namespace dsphp;

abstract class Controller
{
    // 框架对象
    protected $app;
    // 请求信息
    protected $http;
    // 模板对象
    protected $tpl = true;
    // 配置信息
    protected $config = [];
    // 请求控制器
    protected $controller = '';
    // 请求方法
    protected $action = '';
    // 
    protected $logic = false;

    // 构造函数
    public function __construct(App $app, Http $http, array $param = [])
    {
        $this->app  = $app;
        $this->http = $http;

        foreach ($param as $key => $val) {
            if (is_string($key)) {
                $this->$key = $val;
            }
        }

        if ($logic === true) {
            $this->logic = $this->logic();
        }

        $this->initialize();
    }

    // 初始化
    protected function initialize(){}


    /**
     * 缓存
     *
     * @param  string $name  缓存类型
     * @return mixed
     */
    public function cache(string $name)
    {
        $config  = $this->app->getConfig('cache');
        return $this->make('cache', [$config, $name]);
    }

    /**
     * 实例化逻辑
     *
     * @param string $name 逻辑名称
     * @return void
     */
    public function logic(string $name = '', array $argv = [])
    {
        if (empty($name)) {
            if (is_object($this->logic)) {
                return $this->logic;
            }

            $name  = $this->controller;
        }
        
        $logic = $this->app->logic($name, $argv);
        
        $logic->config = $this->config;
        $logic->http   = $this->http; 

        return $logic;
    }

    /**
     * 获取当前请求的安全Key(长度23)
     * 
     * @param boolean $md5 是否md5加密
     */
    public function secureKey(bool $md5 = true): string
    {
        $key = uniqid('', true);
        return $md5 ? md5($key) : $key;
    }

    /**
     * URL生成
     *
     * @param string $url    路由地址
     * @param array  $vars   注入参数（注意顺序） ['val1', 'b'=>'val2']
     * @param array  $vars   get参数 ['a'=>'val1', 'b'=>'val2']
     * @param array  $domain 域名，为空则自动
     */
    public function url(string $url = '', array $bind = [], array $vars = [], bool $domain = false):string
    {
        if ($url) {
            if (! strpos($url, '/')) {
                $url = $this->controller.'/'.$url;
            }
        } else {
            $url = $this->controller.'/'.$this->action;
        }

        $domain = $domain ? $this->config['web_url'] : '/';

        return  $this->http->url($url, $bind, $vars, $domain);
    }

    /**
     * 跳转
     *
     * @param string $url    跳转地址。使用先http->url
     * @param integer $time  等待时间
     * @param string $msg    提示信息
     * @return void
     */
    protected function redirect(string $url, int $time = 0, string $msg = '')
    {
        if (empty($msg)) {
            $msg = "系统将在{$time}秒之后自动跳转到{$url}！";
        }

        if (! headers_sent()) {
            // redirect
            if (0 === $time) {
                header('Location: ' . $url);
            } else {
                header("refresh:{$time};url={$url}");
                echo ($msg);
            }
        } else {
            $str = "<meta http-equiv='Refresh' content='{$time};URL={$url}'>";
            if (0 != $time) {
                $str .= $msg;
            }

            echo $str;
        }

        exit();
    }
}
